<template>
  <div
    ref="titleBarRef"
    class="title-bar"
    @mousedown="handleMouseDown"
    @contextmenu="handleContextMenu"
  >
    <!-- 左侧图标和标题 -->
    <div class="title-bar-left" data-tauri-drag-region>
      <!-- <div class="app-icon" v-if="showIcon">
        <img :src="iconSrc" :alt="title" />
      </div> -->
      <div class="app-title">{{ title }}</div>
    </div>

    <!-- 中间自定义内容插槽 -->
    <div class="title-bar-center">
      <slot name="center"></slot>
    </div>

    <!-- 右侧窗口控制按钮 -->
    <div class="title-bar-right">
      <!-- 自定义按钮 -->
      <div class="custom-buttons" v-if="customButtons && customButtons.length > 0">
        <button
          v-for="button in customButtons"
          :key="button.id"
          :class="['custom-button', button.className]"
          :style="button.style"
          :disabled="button.disabled"
          :title="button.tooltip"
          @click="handleCustomButtonClick(button)"
          v-show="button.visible !== false"
        >
          <span v-if="button.icon" v-html="button.icon"></span>
          <span v-if="button.text">{{ button.text }}</span>
        </button>
      </div>

      <!-- 自定义按钮插槽 -->
      <div class="custom-buttons">
        <slot name="buttons"></slot>
      </div>

      <!-- 窗口控制按钮 -->
      <div class="window-controls" v-if="showControls">
        <button
          v-if="showReduce"
          class="control-button minimize-button"
          @click="minimizeWindow"
        >
          <svg width="12" height="12" viewBox="0 0 12 12">
            <rect x="2" y="5" width="8" height="2" fill="currentColor" />
          </svg>
        </button>

        <button
          v-if="showMaximize"
          class="control-button maximize-button"
          @click="toggleMaximize"
        >
          <svg width="12" height="12" viewBox="0 0 12 12" v-if="!isMaximized">
            <rect
              x="2"
              y="2"
              width="8"
              height="8"
              stroke="currentColor"
              stroke-width="1"
              fill="none"
            />
          </svg>
          <svg width="12" height="12" viewBox="0 0 12 12" v-else>
            <rect
              x="2"
              y="3"
              width="6"
              height="6"
              stroke="currentColor"
              stroke-width="1"
              fill="none"
            />
            <rect
              x="4"
              y="1"
              width="6"
              height="6"
              stroke="currentColor"
              stroke-width="1"
              fill="none"
            />
          </svg>
        </button>

        <button v-if="showClose" class="control-button close-button" @click="closeWindow">
          <svg width="12" height="12" viewBox="0 0 12 12">
            <path
              d="M2 2 L10 10 M10 2 L2 10"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
            />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import { windowManager, themeUtils, titleBarThemes } from "@/utils/titleBarUtils";
import type { TitleBarTheme, CustomButton } from "@/types/titleBar";

interface Props {
  title?: string;
  showIcon?: boolean;
  iconSrc?: string;
  showControls?: boolean;
  minimizeTitle?: string;
  maximizeTitle?: string;
  restoreTitle?: string;
  closeTitle?: string;
  height?: string;
  backgroundColor?: string;
  textColor?: string;
  theme?: keyof typeof titleBarThemes | TitleBarTheme;
  customButtons?: CustomButton[];
  enableDoubleClickMaximize?: boolean;
  enableRightClickMenu?: boolean;
  showMaximize?: boolean;
  showReduce?: boolean;
  showClose?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: "Tauri App",
  showIcon: true,
  iconSrc: "/tauri.svg",
  showControls: true,
  minimizeTitle: "最小化",
  maximizeTitle: "最大化",
  restoreTitle: "还原",
  closeTitle: "关闭",
  height: "32px",
  backgroundColor: "#2c2c2c",
  textColor: "#ffffff",
  theme: "dark",
  customButtons: () => [],
  enableDoubleClickMaximize: true,
  enableRightClickMenu: false,
  showMaximize: false, // 是否显示放大
  showReduce: true, // 是否显示缩放
  showClose: true, // 是否显示关闭
});

const emit = defineEmits<{
  minimize: [];
  maximize: [];
  restore: [];
  close: [];
  doubleClick: [];
  contextMenu: [event: MouseEvent];
  customButtonClick: [button: CustomButton];
}>();

const isMaximized = ref(false);
const titleBarRef = ref<HTMLElement>();

// 计算当前主题
const currentTheme = computed(() => {
  if (typeof props.theme === "string") {
    return themeUtils.getTheme(props.theme);
  } else if (props.theme && themeUtils.validateTheme(props.theme)) {
    return props.theme;
  } else {
    // 使用 props 中的单独样式属性
    return {
      backgroundColor: props.backgroundColor!,
      textColor: props.textColor!,
      height: props.height!,
    } as TitleBarTheme;
  }
});

// 窗口操作方法
const minimizeWindow = async () => {
  try {
    await windowManager.minimize();
    emit("minimize");
  } catch (error) {}
};

const toggleMaximize = async () => {
  try {
    if (isMaximized.value) {
      await windowManager.unmaximize();
      emit("restore");
    } else {
      await windowManager.maximize();
      emit("maximize");
    }
  } catch (error) {}
};

const closeWindow = async () => {
  try {
    await windowManager.close();
    emit("close");
  } catch (error) {}
};

// 鼠标按下处理 - 手动实现拖拽和双击
const handleMouseDown = (event: MouseEvent) => {
  // 只处理左键点击
  if (event.button !== 0) return;

  // 检查是否点击在控制按钮或自定义按钮上
  const target = event.target as HTMLElement;
  if (target.closest(".control-button") || target.closest(".custom-button")) {
    return;
  }

  // 处理双击最大化
  if (event.detail === 2 && props.enableDoubleClickMaximize) {
    // toggleMaximize()
    // emit('doubleClick')
    return;
  }

  // 处理单击拖拽
  if (event.detail === 1) {
    windowManager.startDragging().catch((error: unknown) => {});
  }
};

// 右键菜单
const handleContextMenu = (event: MouseEvent) => {
  if (props.enableRightClickMenu) {
    event.preventDefault();
    emit("contextMenu", event);
  }
};

// 自定义按钮点击
const handleCustomButtonClick = (button: CustomButton) => {
  if (!button.disabled) {
    button.onClick();
    emit("customButtonClick", button);
  }
};

// 监听窗口状态变化
const updateWindowState = async () => {
  try {
    const state = await windowManager.getWindowState();
    isMaximized.value = state.isMaximized;
  } catch (error) {}
};

// 应用主题
const applyTheme = () => {
  if (titleBarRef.value) {
    themeUtils.applyTheme(titleBarRef.value, currentTheme.value);
  }
};

// 监听主题变化
watch(currentTheme, applyTheme, { deep: true });

onMounted(async () => {
  try {
    // 初始化窗口状态
    await updateWindowState();

    // 应用主题
    applyTheme();

    // 监听窗口事件
    const unlistenResize = await windowManager.onResized(updateWindowState);

    // 组件卸载时清理监听器
    onUnmounted(() => {
      unlistenResize();
    });
  } catch (error) {}
});

// 暴露组件方法
defineExpose({
  updateWindowState,
  applyTheme,
  minimize: minimizeWindow,
  maximize: () => windowManager.maximize(),
  unmaximize: () => windowManager.unmaximize(),
  toggleMaximize,
  close: closeWindow,
});
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: var(--title-bar-height, v-bind("currentTheme.height"));
  background-color: var(--title-bar-bg, v-bind("currentTheme.backgroundColor"));
  color: var(--title-bar-color, v-bind("currentTheme.textColor"));
  user-select: none;
  border-bottom: 1px solid var(--title-bar-border, rgba(255, 255, 255, 0.1));
  position: relative;
  z-index: 1000;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

.title-bar-left {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-left: 12px;
  flex-shrink: 0;
}

.app-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.app-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.app-title {
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.title-bar-center {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
  min-width: 0;
  height: 100%;
}

.title-bar-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.custom-buttons {
  display: flex;
  align-items: center;
  gap: 2px;
  margin-right: 4px;
}

.custom-button {
  min-width: 32px;
  height: 24px;
  border: none;
  background: transparent;
  color: inherit;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  border-radius: 4px;
  padding: 0 6px;
  font-size: 12px;
  transition: background-color 0.2s ease;
  outline: none;
}

.custom-button:hover:not(:disabled) {
  background-color: var(--title-bar-hover, rgba(255, 255, 255, 0.1));
}

.custom-button:active:not(:disabled) {
  background-color: var(--title-bar-active, rgba(255, 255, 255, 0.2));
}

.custom-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.window-controls {
  display: flex;
  align-items: center;
}

.control-button {
  width: 46px;
  height: var(--title-bar-height, v-bind("currentTheme.height"));
  border: none;
  background: transparent;
  color: inherit;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
  outline: none;
}

.control-button:hover {
  background-color: var(--title-bar-hover, rgba(255, 255, 255, 0.1));
}

.control-button:active {
  background-color: var(--title-bar-active, rgba(255, 255, 255, 0.2));
}

.close-button:hover {
  background-color: #e81123 !important;
  color: white !important;
}

.close-button:active {
  background-color: #c50e1f !important;
}

/* 确保拖拽区域不会被子元素阻挡 */
.title-bar * {
  pointer-events: auto;
}

.control-button,
.custom-button,
.custom-buttons * {
  pointer-events: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-title {
    max-width: 120px;
  }

  .title-bar-center {
    padding: 0 8px;
  }

  .custom-button {
    min-width: 28px;
    height: 20px;
    font-size: 11px;
  }
}

/* 深色主题特定样式 */
.title-bar[data-theme="dark"] {
  --title-bar-border: rgba(255, 255, 255, 0.1);
  --title-bar-hover: rgba(255, 255, 255, 0.1);
  --title-bar-active: rgba(255, 255, 255, 0.2);
}

/* 浅色主题特定样式 */
.title-bar[data-theme="light"] {
  --title-bar-border: rgba(0, 0, 0, 0.1);
  --title-bar-hover: rgba(0, 0, 0, 0.05);
  --title-bar-active: rgba(0, 0, 0, 0.1);
}
</style>
